//
//  MyOrderViewController.m
//  XYMaterial
//
//  Created by 肖扬 on 16/1/5.
//  Copyright © 2016年 肖扬. All rights reserved.
//

#import "MyOrderViewController.h"
#import "ProductDetailsViewController.h"
//#import "YLSlideView.h"
#import "YLSlideConfig.h"
//#import "YLSlideCell.h"
#import "OrderNullView.h"
#import "OrderModel.h"
#import "orderCell.h"
@interface MyOrderViewController ()<MJRefreshBaseViewDelegate,UITableViewDataSource,UITableViewDelegate,MBProgressHUDDelegate>{
    NSArray *colors;
    NSArray *_testArray;
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    NSMutableArray *fakeData;
    ASIHTTPRequest *asiHttpRequest;
    int Page;

}
@property (nonatomic,strong) NSMutableArray *fakeData;
@property (nonatomic,strong) UIView *selectLineView;
@property (nonatomic,strong) NSString *viewUrl;
@property (nonatomic,strong) NSMutableDictionary *body;
@end

@implementation MyOrderViewController
@synthesize selectLineView,viewUrl,body,fakeData;
-(void)viewWillAppear:(BOOL)animated{
    UISegmentedControl *segmentedControl = (UISegmentedControl *)[self.navigationController.view viewWithTag:121];
    if (segmentedControl==nil) {
        NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"我是供货商",@"我是采购商",nil];
        UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
        segmentedControl.frame = CGRectMake((SWIDTH - 142)/2, 20 + (44 - 26)/2, 142.0, 26);
        segmentedControl.selectedSegmentIndex = 2;//设置默认选择项索引
        segmentedControl.tintColor = [UIColor whiteColor];
        segmentedControl.tag = 121;
        　　//有基本四种样式
        segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;//设置样式
        [segmentedControl addTarget:self action:@selector(segmentAction:)forControlEvents:UIControlEventValueChanged];
        segmentedControl.selectedSegmentIndex = 0;
        [self.navigationController.view addSubview:segmentedControl];
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UISegmentedControl *segmentedControl = (UISegmentedControl *)[self.navigationController.view viewWithTag:121];
    [segmentedControl removeFromSuperview];
    segmentedControl = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.leftBtn addTarget: self action: @selector(goBackAction) forControlEvents: UIControlEventTouchUpInside];
    self.viewUrl = MYSUPPLYORDER;
    self.body = [NSMutableDictionary dictionary];
    [self.body setObject:@"" forKey:@"status"];
    self.fakeData = [NSMutableArray array];
    NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"我是供货商",@"我是采购商",nil];
    //初始化UISegmentedControl
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
    segmentedControl.frame = CGRectMake((SWIDTH - 142)/2, 20 + (44 - 26)/2, 142.0, 26);
    segmentedControl.selectedSegmentIndex = 2;//设置默认选择项索引
    segmentedControl.tintColor = [UIColor whiteColor];
    segmentedControl.tag = 121;
    　　//有基本四种样式
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;//设置样式
    [segmentedControl addTarget:self action:@selector(segmentAction:)forControlEvents:UIControlEventValueChanged];
    segmentedControl.selectedSegmentIndex = 0;
    [self.navigationController.view addSubview:segmentedControl];
    
    OrderNullView *orderView = [[OrderNullView alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, SHEIGHT-108)];
    [orderView setBackgroundColor:[UIColor clearColor]];
    orderView.tag = 101;
    [self.view addSubview:orderView];
    
    NSArray *arr = @[@"全部",
                     @"待付款",
                     @"已付款",
                     @"已发货",
                     @"交易成功"];
    UIView *upView = [self createViewFrame:CGRectMake(0, 64, SWIDTH, 44) bgColor:[UIColor whiteColor] tag:20];
    [self.view addSubview:upView];
    UIView *tempLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 64, 1)];
    self.selectLineView = tempLineView;
    [self.selectLineView setBackgroundColor:UIColorFromRGB(0X177BD0)];
    [upView addSubview:self.selectLineView];
    for(NSInteger i=0;i<[arr count];i++)
    {
        UIButton *button = [self createButtonFrame:CGRectMake((SWIDTH /5)*i, 0, 64, 44) title:[arr objectAtIndex:i] viewController:self selector:@selector(selectClick:) tag:i+10];
        [button setTitleColor:GRAYColor forState:0];
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        button.selected = NO;
        [upView addSubview:button];
        if (i==0) {
            [button setTitleColor:UIColorFromRGB(0x2578c3) forState:0];
        }
    }
    UITableView *tempTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 108, SWIDTH, SHEIGHT - 108)];
    [tempTableView setBackgroundColor:UIColorFromRGB(0xf3f2f2)];
    [tempTableView setDelegate:self];
    [tempTableView setDataSource:self];
    UIView *theView = [[UIView alloc] initWithFrame:self.mainTableView.frame];
    [theView setBackgroundColor:[UIColor clearColor]];
    self.mainTableView.separatorStyle = NO;
    self.mainTableView = tempTableView;
    [self.mainTableView setBackgroundView:theView];
    [self.view addSubview:self.mainTableView];
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTableView.tableFooterView = [[UIView alloc]init];
//        [self.upScrollView setContentSize:CGSizeMake(width, self.upScrollView.frame.size.height)];
    // Do any additional setup after loading the view.
    
    [self addHeader];
    [self addFooter];
}
-(void)segmentAction:(UISegmentedControl *)sender{
    UIView *upView = (UIView *)[self.view viewWithTag:20];
    UIButton *button = (UIButton *)[upView viewWithTag:10];
    button.selected = NO;
    if (sender.selectedSegmentIndex == 0) {
        NSLog(@"点击第一个");
        self.viewUrl = MYSUPPLYORDER;
    }else{
        NSLog(@"点击第二个");
        self.viewUrl = MYPURCHAESORDER;
    }
    [self selectClick:button];
}
-(void)requestOrder{
    TIME
    HEADDIC(nowTime, self.viewUrl);
    NSString *result = [Unity requestSomeApiData:HEAD withBody:self.body];
    NSLog(@"result__%@",result);
    OrderModel *order =[[OrderModel alloc]init];
    [order parseResponseData:result];
    NSMutableDictionary *json = [result objectFromJSONString];
    if ([[json objectForKey:@"err_code"] intValue]==0) {
        if (Page == 1) {
            [self.fakeData removeAllObjects];
        }
        if (order.list.count!=0) {
            [self.fakeData addObjectsFromArray:order.list];
        }
    }
    OrderNullView *orderView = (OrderNullView *)[self.view viewWithTag:101];
    if ([self.fakeData count]==0) {
        [orderView setHidden:NO];
        [self.mainTableView setHidden:YES];
    }else{
        [orderView setHidden:YES];
        [self.mainTableView setHidden:NO];
    }
}
- (void)addFooter
{    __unsafe_unretained MyOrderViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.mainTableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        Page++;
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是footer
        [self.body setObject:[NSNumber numberWithInt:Page] forKey:@"page"];
        
        [vc performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
    };
    _footer = footer;
}

- (void)addHeader
{
    __unsafe_unretained MyOrderViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.mainTableView;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        Page = 1;
        [self.body setObject:[NSNumber numberWithInt:Page] forKey:@"page"];
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是header
        [vc performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                break;
            case MJRefreshStatePulling:
                break;
            case MJRefreshStateRefreshing:
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    [self requestOrder];
    // 刷新表格
    [self.mainTableView reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}


-(void)selectClick:(UIButton *)sender{
    UIButton *tempButton = (UIButton *)sender;
    if (tempButton.selected ==YES) {
        return;
    }
    UIView *view = [self.view viewWithTag:20];
    for (int i = 10; i<15; i++) {
        UIButton *button = (UIButton*)[view viewWithTag:i];
        button.selected = NO;
        [button setTitleColor:GRAYColor forState:0];
    }
    [self.fakeData removeAllObjects];
    Page = 1;
    [self.body setObject:[NSNumber numberWithInt:Page] forKey:@"page"];
    [UIView animateWithDuration:0.4 animations:^{
        [tempButton setTitleColor:UIColorFromRGB(0x2578c3) forState:UIControlStateNormal];
        self.selectLineView.frame = CGRectMake(CGRectGetMinX(sender.frame), 43, sender.frame.size.width, 1);
    }];
    tempButton.selected = YES;
    if (tempButton.tag == 10) {
        [self.body setObject:@"" forKey:@"status"];
    }else if (tempButton.tag == 11){
        [self.body setObject:@"unpay" forKey:@"status"];
    }else if (tempButton.tag == 12){
        [self.body setObject:@"payed" forKey:@"status"];
    }else if (tempButton.tag == 13){
        [self.body setObject:@"shipment" forKey:@"status"];
    }else if (tempButton.tag == 14){
        [self.body setObject:@"success" forKey:@"status"];
    }

    [_header beginRefreshing];
}

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.fakeData count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *Identifier = @"cell";
    orderCell * cell = (orderCell *)[tableView dequeueReusableCellWithIdentifier:Identifier];
    
    if (!cell) {
        cell = [[orderCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    homeModelSupply *model = [self.fakeData objectAtIndex:indexPath.row];
    [cell drawCell:model];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 145;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.viewUrl isEqualToString:MYSUPPLYORDER]) {
        ProductDetailsViewController *productDetailsVC = [[ProductDetailsViewController alloc]init];
        productDetailsVC.supply = [self.fakeData objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:productDetailsVC animated:YES];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
